import React, { Component } from "react";
import { SafeAreaView, Text, View, StyleSheet, TouchableOpacity, Image, TextInput, PermissionsAndroid, Platform, DeviceEventEmitter, ScrollView, Alert } from 'react-native';
import Constant from '../../utils/Constant'//全局变量
import { getImgUrl } from '../../utils/ComFunction';
import HttpUtils from "../../utils/HttpUtils";
import HttpUrls from "../../utils/HttpUrls";
import Header from "../../components/header";
import { ToastToUser } from "../../utils/CustomToast";
import ActionSheet from 'react-native-actionsheet'
import ImageCropPicker from 'react-native-image-crop-picker';
import Upload from '../../components/upload/Upload'
import { requestCameraPermission, requestWritePermission } from '../../utils/Permission';
import Loading from "../../utils/Loading";
import AndroidModule from "../../utils/AndroidConnent";
import PermissionDialog from "../../components/dialog/PermissionDialog";
import AsyncImage from "../../components/image/AsyncImage";

const isIos = Platform.OS == 'ios';

export default class UserInfoPage extends Component {

    constructor(props) {
        super(props);
        this.state = {
            effectiveDate: '',
            memberText: '',
            memberIcon: null,
            isShowVip: false,
            textNum: 0,
            content: '',
            phone: '',
            headImg: '',
            dialogVisible: false,
            fullname: '',
            permissionTitle:'',
            permissionContent:'',
            permissions:[]
        };
    }

    componentDidMount() {
        let that = this
        this.updateUserInfo = DeviceEventEmitter.addListener('commonEvent', e => {
            if (e.type == 'updateUserInfo') {

                if (e.fullname) {
                    that.setState({
                        fullname: e.fullname
                    })
                }
            }
        });

        console.log('Constant.userInfo.face', Constant.userInfo.face)
        this.setState({ headImg: getImgUrl(Constant.userInfo.face), fullname: Constant.userInfo.fullname })
    }

    render() {
        const navigation = this.props.navigation;
        return (
            <View
                style={styles.container}>
                <Header navigation={navigation} Title={'个人资料'} />

                <ScrollView>
                    <TouchableOpacity
                        activeOpacity={0.8}
                        style={styles.menuItem}
                        onPress={() => {
                            this.ActionSheet.show()
                        }}>
                        <Text style={styles.menuText}>帅照</Text>
                        <AsyncImage style={styles.headImg} source={{ uri: this.state.headImg }} />
                        <Image style={styles.arrowImg} source={require('source/image/comm/icon_tree_arrow.png')} />
                    </TouchableOpacity>

                    <TouchableOpacity
                        activeOpacity={0.8}
                        style={[styles.menuItem, { marginTop: 10 }]}
                        onPress={() => {
                            navigation.navigate('ModifyUserInfo')
                        }}>
                        <Text style={styles.menuText}>姓名</Text>
                        <Text style={styles.menuValueText}>{this.state.fullname}</Text>
                        <Image style={styles.arrowImg} source={require('source/image/comm/icon_tree_arrow.png')} />
                    </TouchableOpacity>
                    <TouchableOpacity
                        activeOpacity={1.0}
                        style={[styles.menuItem, { marginTop: 1 }]}
                        onPress={() => {

                        }}>
                        <Text style={styles.menuText}>手机号</Text>
                        <Text style={styles.menuValueText}>{Constant.userInfo.username}</Text>

                    </TouchableOpacity>
                </ScrollView>

                <ActionSheet
                    ref={o => this.ActionSheet = o}
                    title={'请选择照片来源 ?'}
                    options={['相册', '拍照', '取消']}
                    cancelButtonIndex={2}
                    onPress={(index) => { this.selectPhoto(index) }}
                />

                <PermissionDialog
                    visible={this.state.dialogVisible}
                    onClose={() => {
                        this.setState({ dialogVisible: false })
                    }}
                    title={this.state.permissionTitle}
                    content={this.state.permissionContent}
                    permissions={this.state.permissions}
                />

                <Loading onRef={(ref) => (this.Loading = ref)} loadingText={'上传中...'} />

            </View>
        );
    }

    setDialogVisible(dialogVisible,type) {
        if(type == 1){
            this.setState({
                dialogVisible: dialogVisible,
                permissionTitle:'申请相机拍照权限和文件读写存储权限',
                permissionContent:'申请相机拍照权限，用于完成个人头像拍照;申请文件读写权限，用于完成拍照后的图片裁剪保存，完成头像上传',
                permissions:[
                    PermissionsAndroid.PERMISSIONS.CAMERA,
                    PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE
                ]
            })
        }else{
            this.setState({
                dialogVisible: dialogVisible,
                permissionTitle:'申请文件读写存储权限',
                permissionContent:'申请文件读写权限，用于选择本地图片文件，完成头像上传',
                permissions:[PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE]
            })
        }
        
    }

    selectPhoto(index) {
        if (index == 0) {
            if (isIos) {
                this.openPicker()
            }else{

                // PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE, {
                //     title: "存储权限申请",
                //     message: "应用需要访问您的存储空间以保存文件",
                //     buttonPositive: "同意",
                //     buttonNegative: "拒绝",
                //   })
                // this.openPicker()
                
                PermissionsAndroid.check('android.permission.WRITE_EXTERNAL_STORAGE').then(res => {
                    console.log('PermissionsAndroid', res)
                    if (!res) {
                        
                        Alert.alert('申请文件读写存储权限', '申请文件读写权限，用于选择本地图片文件，完成头像上传', [{ text: '拒绝' }, { text: '申请权限', onPress: () => { 
                            this.openPicker()
                        } }])
                    }
                    else {
                        this.openPicker()
                    }
                })
            }


        } else if (index == 1) {
            //照相机
            this.openCamera();
        }
    }

    openPicker() {
        console.log('openPicker')
        //相册
        const option = { mediaType: "photo", cropping: false, compressImageQuality: .8, multiple: false, compressImageMaxWidth: 1024, compressImageMaxHeight: 1024 };
        ImageCropPicker.openPicker(option).then(images => {
            if (this.Loading) {
                this.Loading.show();
            }
            Upload.getAlipz(images.path, Upload.OSS_FACE, this.uploadafterfun);//获取阿里凭证。

        }, (error) => {
            // alert(error);
        });
    }

    openCamera() {
        if (isIos) {
            this.takePhoto()
        } else {
            PermissionsAndroid.check('android.permission.CAMERA').then(res => {
                console.log('PermissionsAndroid', res)
                if (!res) {
                    
                    this.setDialogVisible(true,1)
                }
                else {
                    this.takePhoto()
                }
            })

        }
    }

    takePhoto() {
        const option = { mediaType: "photo", cropping: false, compressImageQuality: .8, compressImageMaxWidth: 1024, compressImageMaxHeight: 1024 };
        ImageCropPicker.openCamera(option).then(images => {
            if (this.Loading) {
                this.Loading.show()
            }
            Upload.getAlipz(images.path, Upload.OSS_FACE, this.uploadafterfun);//获取阿里凭证。

        }, (error) => {
            console.log('takePhoto-error', error);
            // alert(error);
        });
    }

    uploadafterfun = (bojkey) => {
        if (this.Loading) {
            this.Loading.hide();
        }
        Constant.userInfo.face = bojkey
        this.setState({
            headImg: getImgUrl(bojkey)
        }, function () {

        })
        AndroidModule.updateUserInfo({ face: bojkey })
        this.updateUserSubmit(bojkey)
        DeviceEventEmitter.emit('commonEvent', { type: 'updateUserInfo', face: bojkey })
    }



    updateUserSubmit(face) {

        let params = {
            userId: Constant.userInfo.userId,
            face: face
        }

        HttpUtils.postRequest(HttpUrls.updateUser, params)
            .then((result) => {
                let code = result.code
                if (code == 0) {

                }
            })
            .catch((error) => {

            });
    }

};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#f9f9f9',
    },


    menuItem: {
        flexDirection: 'row',
        alignItems: 'center',
        padding: 15,
        backgroundColor: '#FFFFFF',

    },
    menuText: {
        flex: 1,
        fontSize: 16,
        color: '#222222'
    },
    menuValueText: {
        fontSize: 16,
        color: '#222222',
    },
    arrowImg: {
        marginLeft: 10,
        width: 15,
        height: 15
    },
    headImg: {
        width: 60,
        height: 60,
        borderRadius: 60
    }

});